<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="depts"
        :props="props"
        :expand-on-click-node="false"
        icon-class="el-icon-office-building"
        default-expand-all
        highlight-current
      >
        <template #default="{data}">
          <el-row style="width: 100%" type="flex" justify="between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col align="center">{{ data.type }}</el-col>
            <el-col align="center">{{ data.managerName }}</el-col>
            <el-col align="center">{{ data.member || 0 }}人</el-col>
            <el-col align="center">
              <el-button type="text" @click="addDepartment('edit', data.id)">编辑</el-button>
              <el-popconfirm
                title="您确定删除该部门吗？"
                @onConfirm="delDepartment(data.id)"
              >
                <el-button slot="reference" type="text" style="margin: 0 10px">删除</el-button>
              </el-popconfirm>
              <el-button type="text" @click="addDepartment('add', data.id)">新增子项</el-button>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 新增和编辑部门弹层 -->
    <add-dept
      ref="addDept"
      :show-dialog.sync="showDialog"
      :current-pid="currentPid"
      :update:showdialog="updateDialog"
      @addDepartmentSuccess="getDepartments"
    />
  </div>
</template>

<script>
import { getDepartmentList, getDepartmentDetail, delDepartment } from '@/api'
import { transListToTree } from '@/utils'
import AddDept from './components/add-dept.vue'
export default {
  components: {
    AddDept
  },
  data() {
    return {
      // 组织架构列表数据
      depts: [],
      // 读取数据的字段名
      props: { label: 'name' },
      // 控制弹层显示和隐藏
      showDialog: false,
      currentPid: 0
    }
  },
  created() {
    // 获取组织架构列表数据
    this.getDepartments()
  },
  methods: {
    // 获取组织架构列表数据
    async getDepartments() {
      // 调用组织架构列表接口
      const res = await getDepartmentList()
      console.log(res)
      this.depts = transListToTree(res.data, 0)
    },
    updateDialog() {
      this.showDialog = false
    },
    // 新增部门
    addDepartment(type, pid) {
      this.showDialog = true
      // 记录新增部门的pid
      this.currentPid = pid
      // 记录操作类型
      // this.currentType = type
      if (type === 'edit') {
      // 获取并回显要编辑的部门数据
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      }
    },
    // 获取要编辑的部门数据
    async getDepartmentDetail() {
    // 调用获取部门详情接口
      const res = await getDepartmentDetail(this.currentPid)
      this.deptForm = res.data
    }, // 删除部门
    async delDepartment(id) {
      // 调用删除部门接口方法
      console.log(id)
      await delDepartment(id)
      this.$message.success('删除部门成功')
      this.getDepartments()
    }
  }
}
</script>
